//
//  ACollectionViewCell.m
//  CarHome
//
//  Created by dlios on 15-3-23.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "ACollectionViewCell.h"
#import "WifeTableViewCell.h"
#import "AFNetworking.h"
#import "WifeViewController.h"
#import "MJRefresh.h"
#import "WebViewController.h"


@implementation ACollectionViewCell

- (void)dealloc
{
    [_urlBody release];
    [_itemArr release];
    [_data release];
    [_table release];
    [super dealloc];
}



- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.itemArr = [NSMutableArray array];
        self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 80, self.frame.size.width , self.frame.size.height - 60) style:UITableViewStylePlain];
        self.table.delegate = self;
        self.table.dataSource = self;
        [self.table setShowsVerticalScrollIndicator:NO];
        [self.contentView addSubview:_table];
        [_table registerClass:[WifeTableViewCell class] forCellReuseIdentifier:@"cell"];
        [_table release];
        
        [self addObserver:self forKeyPath:@"urlBody" options:NSKeyValueObservingOptionNew context:nil];
        

    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"urlBody"]) {
        [self setupRefresh];
    }
}

#pragma mark - 刷新

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_table addHeaderWithTarget:self action:@selector(headerRereshing)];
    [_table headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_table addFooterWithTarget:self action:@selector(footerRereshing)];
    [_table footerEndRefreshing];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _table.headerPullToRefreshText = @"下拉刷新";
    _table.headerReleaseToRefreshText = @"刷新成功";
    _table.headerRefreshingText = @"正在刷新中";
    
    _table.footerPullToRefreshText = @"上拉加载数据";
    _table.footerReleaseToRefreshText = @"加载数据成功";
    _table.footerRefreshingText = @"加载中";
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    _page = 0;
    [_itemArr removeAllObjects];
    [self startJson];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_table headerEndRefreshing];
    });
}

- (void)footerRereshing
{
    
    // 2.2秒后刷新表格UI
    _page ++;
    [self startJson];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_table footerEndRefreshing];
    });
}








#pragma mark - tableview协议方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"aaaaaaaa%ld", self.itemArr.count);
    return self.itemArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WifeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if ([self.itemArr count] > 0) {
        cell.data = [_itemArr objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}
#pragma mark - cell的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    
    NSLog(@"a");
}

#pragma mark - cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通知中心的使用
    WifeData *data = [self.itemArr objectAtIndex:indexPath.row];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"aa" object:data.topicid];
    

}

#pragma mark - 解析
- (void)startJson
{
    
    NSString *str = self.urlBody;
    NSLog(@"=====%@", str);
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *html = operation.responseString;
        NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
        id dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
       // NSLog(@"%@", dict);
        NSDictionary *dic = dict;
        NSDictionary *dicc = [dic valueForKey:@"result"];
        NSArray *arr = [dicc valueForKey:@"list"];
        for (NSDictionary *dic in arr) {
            WifeData *data = [[WifeData alloc] initWithDictionary:dic];
            [self.itemArr addObject:data];
            [data release];
        }
        [self.table reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"出现错误: %@", error);
    }];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
    
    
}


@end
